package com.lianzhihui.romeex.ui.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.client.android.Intents;
import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.bean.SaveAddressInfo;
import com.lianzhihui.romeex.bean.WalletMainBean;
import com.lianzhihui.romeex.bean.ZZConfigBean;
import com.lianzhihui.romeex.bean.ZZPostBean;
import com.lianzhihui.romeex.config.AppConstants;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.inter.SelectListener;
import com.lianzhihui.romeex.inter.SetListener;
import com.lianzhihui.romeex.mvp.presenter.ZZConfigPresenter;
import com.lianzhihui.romeex.mvp.presenter.ZZPresenter;
import com.lianzhihui.romeex.mvp.view.ZZConfigView;
import com.lianzhihui.romeex.mvp.view.ZZView;
import com.lianzhihui.romeex.ui.base.BaseActivity;
import com.lianzhihui.romeex.ui.me.AddressActivity;
import com.lianzhihui.romeex.ui.qrcode.ScanActivity;
import com.lianzhihui.romeex.utils.CoinUtils;
import com.lianzhihui.romeex.utils.LogUtil;
import com.lianzhihui.romeex.utils.MathUtil;
import com.lianzhihui.romeex.utils.NoDoubleClickUtils;
import com.lianzhihui.romeex.utils.NumberUtils;
import com.lianzhihui.romeex.utils.QrUtils.QRUtils;
import com.lianzhihui.romeex.utils.StringTool;
import com.lianzhihui.romeex.utils.UiUtils;
import com.lianzhihui.romeex.widget.dialog.CoinSelDialog;
import com.lianzhihui.romeex.widget.dialog.ZZFailDialog;
import com.lianzhihui.romeex.widget.dialog.ZZSucDialog;
import com.lianzhihui.romeex.widget.dialog.ZhuanzhangDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description: 转账界面
 * Author: RAMON
 * CreateDate: 2020/11/5 4:06 PM
 * UpdateUser:
 * UpdateDate:
 * UpdateRemark:
 * Version:
 */
public class ZhuanZhangActivity extends BaseActivity implements ZZConfigView, ZZView {

    @BindView(R.id.ll_select)
    LinearLayout ll_select;
    @BindView(R.id.tv_sel)
    TextView tv_sel;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.tv_target)
    TextView tv_target;
    @BindView(R.id.iv_scan)
    ImageView iv_scan;
    @BindView(R.id.iv_address_book)
    ImageView iv_address_book;
    @BindView(R.id.et_sum)
    EditText et_sum;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.tv_suoha)
    TextView tv_suoha;
    @BindView(R.id.tv_canuse)
    TextView tv_canuse;
    @BindView(R.id.tv_service)
    TextView tv_service;
    @BindView(R.id.tv_unit2)
    TextView tv_unit2;
    @BindView(R.id.tv_zhuanzhang_waring)
    TextView tv_zhuanzhang_waring;
    @BindView(R.id.et_remark)
    EditText et_remark;
    @BindView(R.id.bt_submit)
    Button bt_submit;

    WalletMainBean.CoinBean coin;
    ZZConfigBean.ConfigBean config;
    ZZConfigPresenter presenter;
    ZZPresenter bizPresenter;
    boolean canSel = true;
    boolean suohaFlag = false;
    ZZConfigBean bean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zhuanzhang_layout;
    }

    @Override
    protected void initView() {
        setTitle("转账");

        Intent intent = getIntent();
        coin = (WalletMainBean.CoinBean) intent.getSerializableExtra("coin");
        String address = intent.getStringExtra(AppConstants.SCAN_ADDRESS);

        if (!TextUtils.isEmpty(address)) {
            tv_target.setText(address);
        }

        if (coin == null) {
            coin = CoinUtils.getDefCoin();
            //默认 币种
            tv_type.setText(coin.getCoinNameAlias());
            tv_unit.setText(coin.getCoinNameAlias());

        }
        UiUtils.setEditText8(et_sum, new SetListener() {
            @Override
            public void getInput(double content) {
                fee();
            }
        });
//        UiUtils.setEditText(et_sum);
        if (null != coin) {
            tv_type.setText(coin.getCoinNameAlias().isEmpty() ? "" : coin.getCoinNameAlias());
            tv_unit.setText(coin.getCoinNameAlias().isEmpty() ? "" : coin.getCoinNameAlias());
        }
        setOption("转账记录", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, TradeRecordActivity.class);

                if (null != coin) {
                    intent.putExtra("coinName", coin.getCoinName());
                    intent.putExtra("coinNameCobo", coin.getCoinNameCobo());
                    intent.putExtra("coinNameAlias", coin.getCoinNameAlias());
                } else {
                    toast("无数据");
                    return;
                }

                intent.putExtra("tradeType", "1");
                startActivity(intent);
            }
        });

        presenter = new ZZConfigPresenter(this, this);
        bizPresenter = new ZZPresenter(this, this);
        if (null != coin) {
            presenter.getConfig(coin.getCoinName().isEmpty() ? "" : coin.getCoinName(), coin.getCoinNameCobo().isEmpty() ? "" : coin.getCoinNameCobo(), 1);
        }
    }

    @Override
    protected void initData() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCoinSuccess(ZZConfigBean bean) {
        //todo 适配转账数据
        this.bean = bean;
        if (null != bean) {
            config = bean.getConfig();
            tv_canuse.setText(NumberUtils.big8(bean.getBalance()));
        }
        setWarning();
        fee();
    }

    public void setWarning() {
        //文案
        double minMoney = 0;
        if (null != config) {
            minMoney = config.getMinMoney();
        }
        String string = getString(R.string.zhuanzhang_warning_p1) +
                minMoney + " " + coin.getCoinNameAlias() +
                getString(R.string.zhuanzhang_warning_p2);
        tv_zhuanzhang_waring.setText(string);

    }

    public void fee() {
        if (suohaFlag) {
            suohaFlag = false;
            return;
        }
        String fee = "";
        if (null != config && config.getValue().equals("fixed")) {
            //固定 费用
            fee = NumberUtils.big8(config.getFixed());
        }

        if (null != config && config.getValue().equals("rate")) {
            //计算费率
            if (config.getValue().equals("rate")) {
                String sumStr = et_sum.getText().toString();
                double sum = 0D;
                if (TextUtils.isEmpty(sumStr)) {
                    sum = 0D;
                } else {
                    sum = Double.parseDouble(et_sum.getText().toString());
                }
                //计算费率
                double res = MathUtil.multiply(sum, config.getRate());
                fee = NumberUtils.big8(res);
            }
        }
        tv_service.setText(fee);
        if (null != config) {
            tv_unit2.setText(config.getCoinName());
        }

    }

    @Override
    public void onCoinFail(Object obj) {

    }

    @Override
    public void setFailure() {

    }

    @Override
    public void onZZSuccess(String transactionHashcode) {
        dismissLoading();
        EventBus.getDefault().post(new MessageEvent(AppConstants.Event.REFRESHER_ASSETS, true));
        ZZSucDialog sucDialog = new ZZSucDialog(this);
        double sum = Double.parseDouble(et_sum.getText().toString());
        sucDialog.setSum(sum, coin.getCoinNameAlias());
        sucDialog.setListener(new DialogListener() {
            @Override
            public void onPassed() {
                //跳转详情
                Intent intent = new Intent(mActivity, TradeRecordDetailsActivity.class);
                intent.putExtra(AppConstants.RECORD_DETAILS_KEY, transactionHashcode);
                intent.putExtra("tradeType", "1");
                intent.putExtra("coinName", coin.getCoinName());
                startActivity(intent);
                finish();
            }

            @Override
            public void onFail() {

            }
        });
        sucDialog.show();
    }

    @Override
    public void onZZFail() {
        dismissLoading();
        ZZFailDialog failDialog = new ZZFailDialog(this);
        double sum = Double.parseDouble(et_sum.getText().toString());
        failDialog.setSum(sum, coin.getCoinNameAlias());
        failDialog.show();
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == AppConstants.Intent.ADDRESS) {
            //加载地址
            SaveAddressInfo.Address addressBean = (SaveAddressInfo.Address) data.getSerializableExtra("bean");
            tv_target.setText(addressBean.getAddress());
        }
        // 扫描二维码/条码回传
        //todo 二维码 导入私钥回调
        if (requestCode == AppConstants.Intent.SCAN) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(Intents.Scan.RESULT);
                LogUtil.error("ramon", "result: " + content);
                if (TextUtils.isEmpty(content)) {
                    toast("无效二维码");
                    return;
                }

                switch (QRUtils.scanType(content)) {
                    case 1:
                        //转账
                        String scanResult = QRUtils.getContentString(content, 1);
                        String[] split = scanResult.split("_");  // split[0] 数量  split[1] 钱包地址 split[2] 币种
                        String sum = split[0];
                        String address = split[1];
                        coin = CoinUtils.getCoinByAlias(split[2]);
                        //设置数据
                        et_sum.setText(sum);
                        tv_unit.setText(coin.getCoinNameAlias());
                        tv_target.setText(StringTool.addHead(address));
                        tv_type.setText(coin.getCoinNameAlias());
                        presenter.getConfig(coin.getCoinName(), coin.getCoinNameCobo(), 1);
                        break;
                    case 2:
                        //地址
                        String tagAddress = QRUtils.getContentString(content, 2);
                        tv_target.setText(StringTool.addHead(tagAddress));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.bt_submit, R.id.ll_select, R.id.iv_scan, R.id.iv_address_book, R.id.tv_suoha})
    public void onClick(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            switch (view.getId()) {
                case R.id.ll_select:
                    if (canSel) {
                        CoinSelDialog selector = new CoinSelDialog(mActivity);
                        selector.setListener(new SelectListener() {
                            @Override
                            public void onSelect(int position) {
                                coin = selector.adapter.getItem(position);
                                tv_type.setText(coin.getCoinNameAlias());
                                tv_unit.setText(coin.getCoinNameAlias());
                                presenter.getConfig(coin.getCoinName(), coin.getCoinNameCobo(), 1);
                            }
                        });
                        selector.show();
                    }
                    break;

                case R.id.bt_submit:
                    if (bean == null) {
                        toast(getString(R.string.get_data_fail));
                        return;
                    }
                    String tagAddress = tv_target.getText().toString();
                    if (tagAddress.startsWith("ro")) {
                        tagAddress = StringTool.subHead(tagAddress);
                    }
                    if (TextUtils.isEmpty(tagAddress)) {
                        toast(getString(R.string.address_not_null));
                        return;
                    }
                    String inPutStr = et_sum.getText().toString();
                    if (null == et_sum || TextUtils.isEmpty(inPutStr)) {
                        return;
                    }
                    String pat = "^[0-9]+(\\.[0-9]{1,8})?$";
                    boolean matches = Pattern.matches(pat, inPutStr);
                    if ((et_sum.getText().toString().trim().isEmpty() || !matches) || Double.parseDouble(et_sum.getText().toString().trim()) <= 0) {
                        toast(getString(R.string.text_correct_money));
                        return;
                    }
                    double sum = Double.parseDouble(et_sum.getText().toString());
                    double feesum = Double.parseDouble(tv_service.getText().toString());

                    if (sum <= 0) {
                        toast("请输入正确的数量");
                        return;
                    }
                    if (sum < config.getMinMoney()) {
                        toast("转账金额小于最小转账金额");
                        return;
                    }
                    if (null != bean && sum > bean.getBalance()) {
                        toast("转账金额超出可用余额");
                        return;
                    }
                    if (null != bean && feesum > bean.getMainBalance()) {
                        toast("手续费余额不足");
                        return;
                    }
                    ZhuanzhangDialog dialog = new ZhuanzhangDialog(this);
                    dialog.setSum(sum, coin.getCoinName());
                    String finalTagAddress = tagAddress;
                    dialog.setListener(new DialogListener() {
                        @Override
                        public void onPassed() {
                            LogUtil.error("ramon", "success");
                            //转账 逻辑
                            ZZPostBean post = new ZZPostBean();
                            post.setTargetUserAddress(finalTagAddress);
                            post.setCoinName(coin.getCoinName());
                            post.setCoinNameCobo(coin.getCoinNameCobo());
                            post.setRemark(et_remark.getText().toString());
                            post.setAmount(sum);
                            post.setChainType(1);
                            dialog.dismiss();
                            showLoading("");
                            bizPresenter.zzBiz(post);
                        }

                        @Override
                        public void onFail() {
                            toast("安全码错误");
                        }
                    });
                    dialog.show();
                    break;
                case R.id.iv_scan:
                    startActivityForResult(new Intent(this, ScanActivity.class), AppConstants.Intent.SCAN);
                    break;
                case R.id.iv_address_book:
                    Intent intent = new Intent(this, AddressActivity.class);
                    intent.putExtra("isSelect", 0);
                    startActivityForResult(intent, AppConstants.Intent.ADDRESS);
                    break;
                case R.id.tv_suoha:
                    suohaFlag = true;
                    if (null != config && config.getValue().equals("fixed")) {
                        //固定 费用
                        if (null != bean) {
                            double v = bean.getBalance() - config.getFixed();
                            et_sum.setText(NumberUtils.big8(v));
                        }
                    } else {
                        if (null != bean) {
                            double v1 = bean.getBalance() - (config.getFixed() * config.getRate());
                            et_sum.setText(NumberUtils.big8(v1));
                        }

                    }


                    break;
                default:
                    break;
            }
        }
    }

}
